package com.snails.net.retrofit.interceptor;

import android.text.TextUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 请求header中追加公共参数
 * @author  lawrence
 * @date    2019-04-11
 */
public class HeaderInterceptor implements Interceptor {
    private Map<String, String> mHeaderParamsMap = new HashMap<>();

    // **************************************************************************
    // ===== 配置器 =====
    // **************************************************************************
    private HeaderInterceptor(Builder builder) {
        if (builder.headerMap != null
                && builder.headerMap.size() > 0) {
            mHeaderParamsMap.putAll(builder.headerMap);
        }
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // 构造新的request.builder对象，用于追加请求头
        Request.Builder builder = request.newBuilder();

        //添加公共参数,添加到header中
        if (mHeaderParamsMap.size() > 0) {
            for (Map.Entry<String, String> params : mHeaderParamsMap.entrySet()) {
                // header有去重操作，addHeader没有去重
                builder.header(params.getKey(), params.getValue());
            }
        }

        return chain.proceed(builder.build());
    }


    // **************************************************************************
    // ===== 构造器 =====
    // **************************************************************************
    public static class Builder {
        private Map<String, String> headerMap = null;

        private void checkNull() {
            if (headerMap == null) {
                headerMap = new HashMap<>();
            }
        }

        public Builder addHeaderParams(Map<String, String> maps) {
            if (maps != null && maps.size() > 0) {
                checkNull();
                headerMap.putAll(maps);
            }
            return this;
        }

        public Builder addHeaderParams(String key, String value) {
            if (!TextUtils.isEmpty(key)) {
                checkNull();
                headerMap.put(key, value);
            }
            return this;
        }

        public Builder addHeaderParams(String key, int value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, float value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, long value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public Builder addHeaderParams(String key, double value) {
            return addHeaderParams(key, String.valueOf(value));
        }

        public HeaderInterceptor build() {
            return new HeaderInterceptor(this);
        }
    }
}